package Services_Pool;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2023-04-09
 * Time: 20:58
 */

public class MyThreadPool {
    // 管理任务的阻塞队列（本来就是多线程安全）
    private BlockingQueue<Runnable> queue = new LinkedBlockingQueue();

    public void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);
    }

    // 构造固定线程个数的线程池
    public MyThreadPool(int n) {
        for (int i = 0; i < n; i++) {
            Thread t = new Thread(()->{
                while (true) {
                    try {
                        Runnable runnable = queue.take();
                        runnable.run();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            t.start();
        }
    }
}

